import React, { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { atomDark } from 'react-syntax-highlighter/dist/esm/styles/prism';
import Breadcrumb from '../components/common/Breadcrumb';
import BackToTop from '../components/common/BackToTop';
import { blogPosts } from '../data/blogPosts';
import 'github-markdown-css/github-markdown.css';
import './BlogPostPage.css';

const BlogPostPage = () => {
  const { postId } = useParams();
  const [post, setPost] = useState(null);
  const [loading, setLoading] = useState(true);
  const [relatedPosts, setRelatedPosts] = useState([]);
  
  useEffect(() => {
    // 查找当前文章
    const currentPost = blogPosts.find(p => p.id === postId);
    
    if (currentPost) {
      setPost(currentPost);
      
      // 查找相关文章（具有相同标签，但不包括当前文章）
      const related = blogPosts
        .filter(p => 
          p.id !== postId && 
          p.tags.some(tag => currentPost.tags.includes(tag))
        )
        .slice(0, 3);
      
      setRelatedPosts(related);
    }
    
    setLoading(false);
    
    // 滚动到页面顶部
    window.scrollTo(0, 0);
  }, [postId]);

  // 格式化日期
  const formatDate = (dateString) => {
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    return new Date(dateString).toLocaleDateString('zh-CN', options);
  };

  // 动画变体
  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.2
      }
    }
  };

  const itemVariants = {
    hidden: { y: 20, opacity: 0 },
    visible: {
      y: 0,
      opacity: 1,
      transition: {
        duration: 0.5
      }
    }
  };

  // 自定义Markdown渲染组件
  const components = {
    code({node, inline, className, children, ...props}) {
      const match = /language-(\w+)/.exec(className || '');
      return !inline && match ? (
        <SyntaxHighlighter
          style={atomDark}
          language={match[1]}
          PreTag="div"
          showLineNumbers={true}
          {...props}
        >
          {String(children).replace(/\n$/, '')}
        </SyntaxHighlighter>
      ) : (
        <code className={className} {...props}>
          {children}
        </code>
      );
    }
  };

  if (loading) {
    return (
      <div className="loading-container">
        <div className="loader"></div>
      </div>
    );
  }

  if (!post) {
    return (
      <div className="container">
        <div className="error-container">
          <h2>文章未找到</h2>
          <p>抱歉，我们无法找到您请求的文章。</p>
          <Link to="/blog" className="btn btn-primary">
            返回博客
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="blog-post-page">
      <Breadcrumb customPaths={['blog', post.title]} />
      
      <motion.div 
        className="container"
        variants={containerVariants}
        initial="hidden"
        animate="visible"
      >
        <div className="blog-post-container">
          <motion.div className="blog-post-header" variants={itemVariants}>
            <div className="post-meta">
              <span className="post-category">{post.category}</span>
              <span className="post-date">{formatDate(post.date)}</span>
            </div>
            <h1 className="post-title">{post.title}</h1>
            <div className="post-tags">
              {post.tags.map((tag, index) => (
                <Link key={index} to={`/blog?tag=${tag}`} className="post-tag">
                  {tag}
                </Link>
              ))}
            </div>
          </motion.div>
          
          <motion.div className="post-featured-image" variants={itemVariants}>
            <img src={post.coverImage} alt={post.title} />
          </motion.div>
          
          <motion.div 
            className="post-content markdown-body"
            variants={itemVariants}
          >
            <ReactMarkdown 
              remarkPlugins={[remarkGfm]} 
              components={components}
            >
              {post.content}
            </ReactMarkdown>
          </motion.div>
          
          <motion.div className="post-footer" variants={itemVariants}>
            <div className="post-share">
              <span>分享文章：</span>
              <div className="share-buttons">
                {/* 这里可以添加社交分享按钮 */}
                <button className="share-btn">微信</button>
                <button className="share-btn">微博</button>
                <button className="share-btn">LinkedIn</button>
              </div>
            </div>
            
            <div className="post-navigation">
              <Link to="/blog" className="back-to-blog">
                ← 返回博客列表
              </Link>
            </div>
          </motion.div>
        </div>
        
        {relatedPosts.length > 0 && (
          <motion.div className="related-posts" variants={itemVariants}>
            <h2>相关文章</h2>
            <div className="related-posts-grid">
              {relatedPosts.map(relatedPost => (
                <div key={relatedPost.id} className="related-post-card">
                  <div className="related-post-image">
                    <img src={relatedPost.coverImage} alt={relatedPost.title} />
                  </div>
                  <div className="related-post-content">
                    <span className="related-post-date">
                      {formatDate(relatedPost.date)}
                    </span>
                    <h3 className="related-post-title">
                      <Link to={`/blog/${relatedPost.id}`}>
                        {relatedPost.title}
                      </Link>
                    </h3>
                    <Link to={`/blog/${relatedPost.id}`} className="read-more">
                      阅读全文
                    </Link>
                  </div>
                </div>
              ))}
            </div>
          </motion.div>
        )}
      </motion.div>
      
      <BackToTop />
    </div>
  );
};

export default BlogPostPage;
